package server;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Crypto {
	
	/**
	 * Hashes a string with SHA-1 and returns the result as a hex
	 * string (more human readable).
	 * 
	 * @param s String to be hashed
	 * @return Hex of the digest
	 */
	public static String hash(String s) {
		MessageDigest digest;
		String ret = null;
		try {
			digest = MessageDigest.getInstance("SHA-1");
			digest.update(s.getBytes("UTF-8"));
			ret = toHex(digest.digest());
		} 
		catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} 
		catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		return ret;
	}
	
	/**
	 * Converts a byte string to hex values.
	 * 
	 * @param b Byte string
	 * @return Hex representation of the byte string
	 */
	public static String toHex(byte[] b) {
		String result = "";
		for (int i=0; i < b.length; i++) {
			result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
		}
		return result;
	}
}
